<?php

class Router {

	parse_url() {
	
	}

	// put segments into array form
	$segments = explode(  '/', urldecode( rtrim($_SERVER['PHP_SELF'], '/') ) );
	// trim the array up to and including the script name 
	$controllerName = '';
	while( $controllerName != basename(__FILE__) && count( $segments ) > 0 ) { 
		$controllerName = array_shift( $segments );
	}
	// no segments after script name, load the default controller
	if( count( $segments ) === 0 ) echo "zero\n";//$controller = new Default();
	// there's a controller specified. See if it exists
	else {
		// build the segments one by one as a controller path
		$length = count( $segments );
		for( $offset = 1; $offset <= $length; $offset++ ) {
			$controllerPath = implode('/', array_slice($segments, 0, $offset ) );
			if( file_exists( "lib/controllers/$controllerPath.php" ) ) {
				require("lib/controllers/$controllerPath.php");
				$controllerName = $segments[$offset-1];
				break;
			}
		}
		
		// we ran out of segments, but we found a controller with no arguments
		// load the controller, and its default method, the index
		if( $offset == $length ) {
			$controller = new $controllerName();
			if( is_callable( array($controller, 'index') ) ) call_user_func_array( array( $controller, 'index'), array_slice($segments, ++$offset ) ) ;
			else echo 'Could not find proper class.';
			
		}
		
		// if we did not run out of segments then we know that there is still 
		// the method and optionally the arguments
		else if( $offset < $length ) {
			$controller = new $controllerName();
			$methodName = $segments[$offset];
			if( is_callable( array($controller, $methodName) ) ) call_user_func_array( array( $controller, $methodName), array_slice($segments, ++$offset ) ) ;
			echo 'Could not find proper class.';
		}
		
		// at this point we do not have any controllers present. Show an error message.
		else {
			echo 'Could not find proper class.';
		}
	}

}